const {
  getUserListService,
  getUserNum,
  updateUser,
  deleteUserById,
  getUserByName,
} = require("../service/user.service");

class UserController {
  // 获取用户列表
  async getUserList(ctx, next) {
    //获取用户列表
    try {
      // 获取用户总数
      const total = await getUserNum();
      //获取用户列表
      const res = await getUserListService();

      ctx.body = {
        data: { total: total.total, res },
        meta: {
          msg: "获取成功",
          status: 200,
        },
      };
      console.log("获取用户列表成功");
    } catch {
      return ctx.app.emit("error", new Error("用户列表获取失败"), ctx);
    }
  }

  // 通过用户name查询到这个用户
  async getUserInfo(ctx, next) {
    console.log(ctx.request.params.name);
    const res = await getUserByName(ctx.request.params.name);
    // console.log(res);
    ctx.body = res[0];
  }

  async updateUser(ctx, next) {
    const { id } = ctx.request.params;
    const user = ctx.request.body;
    const result = await updateUser(id, user);
    if (result.length >= 1)
      return (ctx.body = {
        msg: "修改用户信息成功",
        status: 200,
      });
    else return ctx.app.emit("error", new Error("更改用户失败"), ctx);
  }

  async deleteUser(ctx, next) {
    const { id } = ctx.request.params;
    const result = await deleteUserById(id);
    if (result.length >= 1)
      return (ctx.body = {
        msg: "删除用户成功",
        status: 200,
      });
    else return ctx.app.emit("error", new Error("删除用户失败"), ctx);
  }
}

module.exports = new UserController();
